package cn.zjj.org.service.impl;

import cn.zjj.basic.query.BaseQuery;
import cn.zjj.basic.service.impl.BaseServiceImpl;
import cn.zjj.basic.util.PageList;
import cn.zjj.org.domain.Department;
import cn.zjj.org.mapper.DepartmentMapper;
import cn.zjj.org.query.DepartmentQuery;
import cn.zjj.org.service.IDepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
@Service
public class DepartmentServiceImpl extends BaseServiceImpl<Department> implements IDepartmentService {

    @Autowired
    private DepartmentMapper departmentMapper;




    //添加
    @Transactional
    @Override
    public void insert(Department department) {
        departmentMapper.insert(department);
        //修改也要用,直接调用修改就行
        update(department);

    }

    //修改
    @Transactional
    @Override
    public void update(Department department) {

        if(department.getParent_id()==null){
            //以下 修改和添加共用
            Long id = department.getId();
            //如果是顶级部门,dirpath就直接是 / +本部id
            department.setDirPath("/"+id);
        }else{
            //非顶级部门,dirpath为  上级部门dirpath+/+本部id
            Department parentDept = departmentMapper.selectById(department.getParent_id());
            department.setDirPath(parentDept.getDirPath()+"/"+department.getId());
        }


        departmentMapper.update(department);
    }


    //表单界面部门树返回值
    @Override
    public List<Department> deptTree() {
        //查询所有
        List<Department> departments = departmentMapper.selectAll();

        //获取所有的部门和其id 放入键值对中,方便后续操作
        HashMap<Long, Department> map = new HashMap<>();
        for (Department department : departments) {
                map.put(department.getId(),department);
        }

        //获得部门树 1 /2 /3
        List<Department> deptTree = new ArrayList<>();//  department 1

        for (Department department : departments) {
            //如果是没有parent_id的就是顶级部门直接放入deptTree
            if(department.getParent_id()==null){
                deptTree.add(department);
            }else{
                //有parent_id就放入对应部门的子集部门集合,child集合

                //获取对应的父级部门id
                Long parent_id = department.getParent_id();

                //根据parent_id查出对应的父级(顶级部门也在map中)

                //这种每次都是从数据库中查的,都是新的,child都是空的
                /*Department deptParent = selectById(parent_id);*/

                //这种从内存中查出来的,存进去都是有数据child的
                Department deptParent = map.get(parent_id);

                //放入对应父级的子集集合
                deptParent.getChildren().add(department);
            }
        }
        return deptTree;
    }
}
